/*
 * Copyright (c) 2020 Carnegie Lee
 * All rights reserved
 */
package com.geekc.rabbitmq.consumer;

import com.geekc.rabbitmq.constant.RabbitMQConst;
import com.geekc.rabbitmq.domain.Message;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * 死信消费者
 * @author Carnegie Lee
 */
@Component
public class DlxConsumer {

    @RabbitHandler
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = RabbitMQConst.RABBITMQ_DLX_QUEUE_NAME, durable = "true"),
                    exchange = @Exchange(value = RabbitMQConst.RABBITMQ_DLX_EXCHANGE_NAME, durable = "true", type = "topic"),
                    key = "#"
            )
    )
    public void dlxMessageHandler(@Payload Message message, Channel channel, @Headers Map<String, Object> headers) {
        System.out.println("接收到死信[id:" + message.getMessageId() + ",body:" + message.getMessageBody() + "]");
        //TODO
        /** 签收消息 */
        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        try {
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
